package com.itboye.mengwu.ui.shop;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.config.GlobalConfig;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.DensityUtil;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.XImageLoader;
import com.itboye.mengwu.R;
import com.itboye.mengwu.address.BaseDialogFragment;
import com.itboye.mengwu.app.ui.mymeng.IntegerParse;
import com.itboye.mengwu.data.model.ShopCarBean;
import com.itboye.mengwu.data.presenter.PayPresenter;
import com.itboye.mengwu.data.presenter.ShopCarPresenter;
import com.itboye.mengwu.ui.shop.DaPaiGouRootBean.A.SkuList;
import com.itboye.mengwu.ui.shop.DaPaiGouRootBean.A.SkuName;
import com.itboye.mengwu.widget.XScrollView;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.Animator.AnimatorListener;
import com.nineoldandroids.animation.ObjectAnimator;

public class DapPeiGouJiaRuGouWuCheDialog extends BaseDialogFragment implements
		Observer {

	View close;
	ImageView pic;
	TextView jiege;
	TextView kucun;
	ViewGroup guigeContainer;
	View ok;
	DaPaiGouRootBean.A goodsDetailBeans;
	int position;
	View jian;
	View jia;
	EditText input;
	boolean isLiJIGouMai;
	ViewGroup container;
	String imgUrl;
	ShopCarPresenter presener;
	PayPresenter payPresenter;
	protected String price;

	public DapPeiGouJiaRuGouWuCheDialog() {

	}

	public DapPeiGouJiaRuGouWuCheDialog(int position,
			DaPaiGouRootBean.A goodsDetailBeans, boolean isLiJIGouMai) {
		this.position = position;
		this.goodsDetailBeans = goodsDetailBeans;
		this.isLiJIGouMai = isLiJIGouMai;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		return LayoutInflater.from(getContext()).inflate(
				R.layout.dialogfragment_jiarugouwuche, null);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {

		super.onActivityCreated(savedInstanceState);
		presener = new ShopCarPresenter(this);
		payPresenter = new PayPresenter(this);
		// if (savedInstanceState != null) {
		// goodsDetailBeans = (DapeigouBean) savedInstanceState
		// .getSerializable("goodsDetailBeans");
		// isLiJIGouMai = savedInstanceState.getBoolean("isLiJIGouMai");
		// }
		imgUrl = goodsDetailBeans.getMainImg();
		XImageLoader.load(GlobalConfig.API_URL + "/picture/index?id="
				+ goodsDetailBeans.getMainImg(), pic);
		// jiege.setText("￥" + goodsDetailBeans.getMinPrice());
		//
		int hasSuk = Integer.parseInt(goodsDetailBeans.getHasSku());
		if (hasSuk == 1) {// 多规格
			addGuiGe();
		} else {// 单规格
			((View) kucun.getParent()).setVisibility(View.VISIBLE);
			// if (goodsDetailBeans.getSkuInfo() != null
			// && goodsDetailBeans.getSkuList().size() > 0) {
			// kucun.setText(goodsDetailBeans.get
			// .getQuantity()
			// + "");
			// }

		}

		jia.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String s = input.getText().toString();
				try {
					int c = Integer.parseInt(s);
					input.setText(c + 1 + "");
				} catch (NumberFormatException e) {
					input.setText("1");
				}
				input.setSelection(input.getText().length());
			}
		});

		jian.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String s = input.getText().toString();
				try {
					int c = Integer.parseInt(s);
					if (c > 0) {
						c--;
					}
					input.setText(c + "");
				} catch (NumberFormatException e) {
					input.setText("0");
				}
				input.setSelection(input.getText().length());
			}
		});

		close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				close();
			}
		});
		ok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String s = checkGuiGeSelectedState();
				if (s == null) {
					return;
				}

//				if (IntegerParse.parse(kucun.getText().toString(), 0) < IntegerParse
//						.parse(input.getText().toString(), 0)) {
//					Toast.makeText(getContext(), "库存不足", 1).show();
//					// return;
//				}

				// int hasSuk =
				// Integer.parseInt(goodsDetailBeans.getHasSku());//1、单规格0、多规格
				String pskuId = "";
				String skuDesc = "";
				String imgId = "";
				List<SkuList> list = goodsDetailBeans.getSkuList();
				for (SkuList skuCombinationBean : list) {
					if (skuCombinationBean.getSkuId().equals(s)) {
						pskuId = skuCombinationBean.getId();
						skuDesc = skuCombinationBean.getSkuDesc();
						imgId = skuCombinationBean.getIconUrl();
						break;
					}
				}
//				ByAlert.alert(pskuId+"");
				Intent intent = new Intent("select");
				intent.putExtra("skuDesc", skuDesc);
				intent.putExtra("position", position);
				intent.putExtra("id", pskuId);
				intent.putExtra("img", imgId);
				intent.putExtra("counts", IntegerParse.parse(input.getText().toString(), 0));
				getActivity().sendBroadcast(intent);
				close();
			}
		});

		pic.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (imgUrl != null) {
					// ImageViewerDialog imageViewerDialog = new
					// ImageViewerDialog(
					// getActivity());
					// String urls[] = new String[] { imgUrl };
					// imageViewerDialog.setImageUrls(urls);
					// imageViewerDialog.show(0);
				}

			}
		});
	}

	public static final String EVENT_TYPE_UNKNOWN = BaseActivity.class
			.getName() + "_unknown";

	public ResultEntity handlerError(Object data) {
		ResultEntity result = (ResultEntity) data;
		if (result == null) {
			result = new ResultEntity("-1", "数据格式错误!~", data);
			return result;
		}

		if (result.hasError()) {
			ByAlert.alert(result.getMsg());
			result.setEventType(EVENT_TYPE_UNKNOWN);
			return result;
		}

		return result;
	}

	protected String checkGuiGeSelectedState() {

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < guigeContainer.getChildCount(); i++) {
			View vv = guigeContainer.getChildAt(i);
			if (!(vv instanceof FlowLayout)) {
				continue;
			}
			FlowLayout flowLayout = (FlowLayout) vv;
			int j;
			for (j = 0; j < flowLayout.getChildCount(); j++) {
				TextView textView = (TextView) flowLayout.getChildAt(j);
				if (textView.isSelected()) {
					sb.append(textView.getTag() + ";");
					break;
				}
			}
			if (j == flowLayout.getChildCount()) {
				// Toast.makeText(
				// getContext(),
				// "请选择"
				// + goodsDetailBeans.getSkuName().get(i / 2)
				// .getId(), 1).show();
				return null;
			}
		}

		return sb.toString();
	}

	private void addGuiGe() {

		List<SkuName> list = goodsDetailBeans.getSkuName();
		for (int i = 0; i < list.size(); i++) {
			SkuName skuBean = list.get(i);
			TextView title = createTitle(skuBean.getId());
			guigeContainer.addView(title);

			FlowLayout flowLayout = createFlowLayout(skuBean.getVid(),
					goodsDetailBeans.getSkuId().get(i).getId() + "",
					goodsDetailBeans.getSkuId().get(i).getVid());
			guigeContainer.addView(flowLayout);
		}
		container.getViewTreeObserver().addOnGlobalLayoutListener(
				new OnGlobalLayoutListener() {

					@SuppressLint("NewApi")
					@Override
					public void onGlobalLayout() {
						try {
							container.getViewTreeObserver()
									.removeGlobalOnLayoutListener(this);
						} catch (Throwable e) {

						}

						if (container.getHeight() > DensityUtil.screenHeigh() * 0.7) {

							int h = DensityUtil.screenHeigh()
									- DensityUtil.dip2px(280);
							XScrollView scrollView = new XScrollView(
									getContext());
							scrollView.setLayoutParams(new LayoutParams(
									LayoutParams.MATCH_PARENT, h));

							ViewGroup vg = (ViewGroup) guigeContainer
									.getParent();
							vg.removeView(guigeContainer);

							scrollView.addView(guigeContainer);
							vg.addView(scrollView);
						}

					}
				});

	}

	private OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			try {
				kucun.setText(null);
				jiege.setText(null);
				if (v.isSelected()) {
					v.setSelected(false);
					((TextView) v).setTextColor(Color.BLACK);
					imgUrl = goodsDetailBeans.getMainImg();
					if ((!goodsDetailBeans.getMainImg().isEmpty())
							& goodsDetailBeans.getMainImg() != null) {
						XImageLoader.load(
								GlobalConfig.API_URL + "/picture/index?id="
										+ goodsDetailBeans.getMainImg(), pic);
					}
					return;
				}
				FlowLayout clickTextViewParent = null;
				StringBuilder stringBuilder = new StringBuilder();

				for (int i = 0; i < guigeContainer.getChildCount(); i++) {
					View view = guigeContainer.getChildAt(i);
					if (!(view instanceof FlowLayout)) {

						continue;
					}

					FlowLayout flowLayout = (FlowLayout) view;
					if (v.getParent() == flowLayout) {
						clickTextViewParent = flowLayout;
						stringBuilder.append(v.getTag());
						stringBuilder.append(";");

					} else {
						for (int j = 0; j < flowLayout.getChildCount(); j++) {
							View textview = flowLayout.getChildAt(j);
							if (textview.isSelected()) {
								stringBuilder.append(textview.getTag());
								stringBuilder.append(";");
								break;
							}
						}
					}

				}

				List<SkuList> skuList = goodsDetailBeans.getSkuList();
				String selectedSku = stringBuilder.toString();
				for (SkuList skuCombinationBean : skuList) {
					String sku = skuCombinationBean.getSkuId();

					if (sku.contains(selectedSku)) {
						for (int j = 0; j < clickTextViewParent.getChildCount(); j++) {
							if (clickTextViewParent.getChildAt(j).isSelected()) {
								clickTextViewParent.getChildAt(j).setSelected(
										false);
								((TextView) clickTextViewParent.getChildAt(j))
										.setTextColor(Color.BLACK);
								break;
							}
						}
						v.setSelected(true);
						((TextView) v).setTextColor(Color.WHITE);
						break;
					}
				}

				String s = isAllFenLeiSelected();
				//
				if (s != null) {
					((View) kucun.getParent()).setVisibility(View.VISIBLE);
					List<SkuList> list = goodsDetailBeans.getSkuList();
					for (SkuList skuCombinationBean : list) {
						if (skuCombinationBean.getSkuId().equals(s)) {
							// kucun.setText(skuCombinationBean.getQuantity() +
							// "");
							// price= skuCombinationBean.getPrice();
							// jiege.setText("￥" +
							// skuCombinationBean.getPrice());
							if (TextUtils.isEmpty(skuCombinationBean
									.getIconUrl())) {
								XImageLoader.load(GlobalConfig.API_URL
										+ "/picture/index?id="
										+ goodsDetailBeans.getMainImg(), pic);
								imgUrl = goodsDetailBeans.getMainImg();
							} else {
								XImageLoader.load(GlobalConfig.API_URL
										+ "/picture/index?id="
										+ skuCombinationBean.getIconUrl(), pic);
								imgUrl = skuCombinationBean.getIconUrl();
							}
							break;
						}
					}
				} else {
					((View) kucun.getParent()).setVisibility(View.INVISIBLE);

				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	};

	private String isAllFenLeiSelected() {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < guigeContainer.getChildCount(); i++) {
			View vv = guigeContainer.getChildAt(i);
			if (!(vv instanceof FlowLayout)) {
				continue;
			}
			FlowLayout flowLayout = (FlowLayout) vv;
			int j;
			for (j = 0; j < flowLayout.getChildCount(); j++) {
				TextView textView = (TextView) flowLayout.getChildAt(j);
				if (textView.isSelected()) {
					sb.append(textView.getTag() + ";");
					break;
				}
			}
			if (j == flowLayout.getChildCount()) {
				return null;
			}
		}

		return sb.toString();

	}

	/**
	 * 当前已选中的规格集合
	 * 
	 * @return
	 */
	protected List<String> selectedGuige() {

		List<String> selectedGuige = new ArrayList<String>();
		for (int i = 0; i < guigeContainer.getChildCount(); i++) {
			View vv = guigeContainer.getChildAt(i);
			if (!(vv instanceof FlowLayout)) {
				continue;
			}
			FlowLayout flowLayout = (FlowLayout) vv;
			for (int j = 0; j < flowLayout.getChildCount(); j++) {
				TextView textView = (TextView) flowLayout.getChildAt(j);
				if (textView.isSelected()) {
					selectedGuige.add((String) textView.getTag());
				}

			}

		}
		return selectedGuige;
	}

	private FlowLayout createFlowLayout(List<String> vid, String id,
			List<String> vids) {

		int dis = DensityUtil.dip2px(5);
		FlowLayout flowLayout = new FlowLayout(getContext());
		for (int i = 0; i < vid.size(); i++) {
			TextView textView = new TextView(getContext());
			textView.setTextColor(Color.BLACK);
			textView.setBackgroundResource(R.drawable.selector_guige);

			textView.setText(vid.get(i));

			textView.setTag(id + ":" + vids.get(i));

			textView.setOnClickListener(clickListener);
			ViewGroup.MarginLayoutParams marginLayoutParams = new ViewGroup.MarginLayoutParams(
					ViewGroup.LayoutParams.WRAP_CONTENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);

			marginLayoutParams.setMargins(dis, dis, dis, dis);
			textView.setLayoutParams(marginLayoutParams);
			flowLayout.addView(textView);
		}

		return flowLayout;
	}

	/**
	 * 设置套餐一、套餐二等标题栏
	 * 
	 * @param s
	 * @return
	 */
	private TextView createTitle(String s) {
		TextView textView = new TextView(getContext());
		textView.setText(s);
		textView.setTextColor(Color.BLACK);

		return textView;
	}

	public void close() {

		View v = getView().findViewById(R.id.container);
		ObjectAnimator animator = ObjectAnimator.ofFloat(v, "translationY", 0,
				v.getHeight()).setDuration(300);

		animator.addListener(new AnimatorListener() {

			@Override
			public void onAnimationStart(Animator arg0) {
			}

			@Override
			public void onAnimationRepeat(Animator arg0) {
			}

			@Override
			public void onAnimationEnd(Animator arg0) {

				dismiss();
			}

			@Override
			public void onAnimationCancel(Animator arg0) {
				dismiss();
			}
		});

		animator.start();
	}

	@Override
	public void onSaveInstanceState(Bundle arg0) {

		super.onSaveInstanceState(arg0);

		// arg0.putSerializable("goodsDetailBeans", goodsDetailBeans);
		// arg0.putBoolean("isLiJIGouMai", isLiJIGouMai);
	}

	@Override
	public void update(Observable observable, Object data) {
		ResultEntity entity = handlerError(data);
//		ByAlert.alert(entity.getData() + "");
		if (entity != null) {
			if (entity.getEventType() == ShopCarPresenter.ShopCarAdd_success) {
				ByAlert.alert("添加成功");
				Intent intent = new Intent("changeshopcart");
				getActivity().sendBroadcast(intent);
				dismiss();
			} else if (entity.getEventType() == ShopCarPresenter.ShopCarAddFailEvent) {
				ByAlert.alert("添加失败");
			}
		}
	}

}
